<?php
namespace api\modules\mp\models;

use yii\base\Model;
use common\tool\Curd;
use yii\web\NotFoundHttpException;

class Feedback extends Model {
    use Curd;

    public static function tableName() {
        return 'mp_feedback';
    }

    public function rules() {
        return [
            [
                [
                    'content',
                ],
                'required'
            ],
            [
                [

                    'openid',
                    'content',
                ],
                'string'
            ],
            [
                [
                    'ctime',
                ],
                'datetime',
                'format' => 'yyyy-MM-dd HH:mm:ss'
            ],
        ];
    }

    public static function build($data = []): ?self {
        if (!empty($data['id'])) {
            $one = self::getOne("id={$data['id']}");
            if (!$one) throw new NotFoundHttpException();
            $data = array_merge($one, $data);
        }
        return new self($data);
    }

    public $id;
    public $content;
    public $openid;
    public $ctime;
    public $via='';

    public function save() {
        $data = [
            'content' => $this->content,
            'openid' => $this->openid,
            'ctime' => $this->ctime,
            'via' => $this->via,
        ];
        $now = date('Y-m-d H:i:s');
        if ($this->id) {
            self::update($data, 'id=:id', [':id' => $this->id]);
        } else {
            $data['ctime'] = $now;
            $id = self::insert($data);
            $this->id = $id;
        }
    }

    public function info() {
        return $this->getAttributes();
    }
}
